<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">
          {{ title }}
        </h3>
      </div>
      <el-form-item prop="userName">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          v-model="loginForm.userName"
          placeholder="用户名"
          name="userName"
          type="text"
          tabindex="1"
          autocomplete="on"
        ></el-input>
      </el-form-item>
      <el-tooltip
        v-model="capsTooltip"
        content="大写输入已经打开"
        placement="right"
        manual
      >
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="Password"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </el-tooltip>
      <!--      <el-form-item>-->
      <!--        <LoginDargVerify-->
      <!--          ref="verify"-->
      <!--          @isVerifySuccess="verifyCb"-->
      <!--        ></LoginDargVerify>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          style="width: 60%"
          v-model="verifyInput"
          placeholder="请输入验证码"
          name="userName"
          type="text"
          @keyup.enter="handleLogin"
        ></el-input>
        <identity :identifyCode="verifyCode" @click="updateCode"></identity>
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.prevent="handleLogin"
      >
        登录
      </el-button>
    </el-form>
    <div class="infohub">
      <div class="helpHub">
        <router-link to=""><span>帮助</span></router-link>
        <router-link to=""><span>隐私</span></router-link>
        <router-link to=""><span>条款</span></router-link>
      </div>
      <br />
      <span>copyright 2019-2021 广州市融畅智联医疗科技有限公司</span>
    </div>
    <node-table
      title="请选择您要登录的节点"
      :list="dataList"
      v-model="isShowNode"
      @nodeChage="selectClick"
    ></node-table>
  </div>
  <el-dialog title="请输入登录验证码" v-model="isVerify" width="40%">
    <el-form>
      <el-form-item label="验证码：">
        <identity
          style="height: 150px"
          :identifyCode="verifyCode"
          :contentWidth="350"
          :contentHeight="120"
          :fontSizeMax="90"
          :fontSizeMin="70"
        ></identity>
      </el-form-item>
      <el-form-item label="请输入：" :required="true">
        <el-input v-model="verifyInput" style="width: 150px"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="warning" @click="updateCode">
          看不清?点击更换
        </el-button>
        <el-button @click="isVerify = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
  import store from '@/store/index'
  import NodeTable from '@/components/NodeTable'
  // import LoginDargVerify from '@/components/LoginDargVerify'
  import identity from '@/components/Identify'

  import { loadNode } from '@/api/user'
  import common from '@/utils/common'
  import md5 from 'md5'
  export default {
    components: { NodeTable, identity },
    data() {
      const validateuserName = (rule, value, callback) => {
        if (!value || value.length < 4) {
          callback(new Error('用户名不符合规范，请重新输入您的用户名'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (!value || value.length < 4) {
          callback(new Error('密码不符合规范，请重新输入您的密码'))
        } else {
          callback()
        }
      }
      const code = common.randomWord(4)
      return {
        loginForm: {
          userName: null,
          password: null,
        },
        loginRules: {
          userName: [
            { required: true, trigger: 'blur', validator: validateuserName },
          ],
          password: [
            { required: true, trigger: 'blur', validator: validatePassword },
          ],
        },
        capsTooltip: false,
        passwordType: 'password',
        loading: false,
        redirect: null,
        otherQuery: {},
        isShowNode: false,
        dataList: null,
        isVerify: false,
        verifyCode: code,
        verifyInput: null,
      }
    },
    watch: {
      $route: {
        handler: function (route) {
          const query = route.query
          if (query) {
            this.redirect = query.redirect
            this.otherQuery = this.getOtherQuery(query.redirect)
          }
        },
        immediate: true,
      },
    },
    computed: {
      title() {
        return process.env.VUE_APP_NAME || '全病程管理系统'
      },
    },
    methods: {
      checkCapslock(e) {
        const { key } = e
        this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        // if (!this.isVerifySuccess) {
        //   common.XmMessage(1, '请通过滑轨验证')
        //   return
        // }

        this.$refs.loginForm.validate(async (valid) => {
          console.log('点击了登录' + JSON.stringify(this.loginForm))

          if (valid) {
            // this.isVerify = true
            // this.verifyInput = null
            // this.updateCode()
            this.onSubmit()
          } else {
            this.resetVerify()
            return false
          }
        })
      },
      onSubmit() {
        if (!this.verifyInput) {
          common.XmMessage(1, '请选填写验证码')
          this.updateCode()
          return
        } else if (
          this.verifyInput.toLowerCase() !== this.verifyCode.toLowerCase()
        ) {
          common.XmMessage(1, '填写错误')
          this.updateCode()
          return
        }
        this.loadNode()
      },
      async loadNode() {
        this.loading = true
        const { userName, password } = this.loginForm
        const res = await loadNode({
          userName,
          password: common.addSalt(md5(password)),
        }).catch(() => {
          this.resetVerify()
          this.loading = false
        })
        this.loading = false
        if (!res) return
        if (res.data.length > 1) {
          // 多节点用户自己选择
          this.isShowNode = true
          this.dataList = res.data
        } else {
          // 单节点自己选择
          store.dispatch('user/setNode', res.data[0])
          this.selectClick(res.data[0])
          console.log('nodeInfo', JSON.stringify(store.getters.nodeInfo))
        }
      },
      login(userName, password, orgId) {
        //  增加验证码

        store
          .dispatch('user/login', { userName, password, orgId })
          .then(() => {
            this.$router.push({
              path: this.redirect || '/',
              query: this.otherQuery,
            })
          })
          .catch(() => {
            this.resetVerify()
          })
      },
      updateCode() {
        this.verifyCode = common.randomWord(4)
      },
      getOtherQuery(query) {
        return common.getQueryString(query)
        //
        // return Object.keys(query).reduce((acc, cur) => {
        //   if (cur !== 'redirect') {
        //     acc[cur] = query[cur]
        //   }
        //   return acc
        // }, {})
      },
      selectClick(val) {
        this.isShowNode = false
        this.login(this.loginForm.userName, this.loginForm.password, val.id)
      },
      verifyCb(isVerifySuccess) {
        this.isVerifySuccess = isVerifySuccess
      },
      resetVerify() {
        // TODO this.$refs.verify.reset 为啥返回的是 promise
        //
        // console.log('this.$refs.verify.reset =' + this.$refs.verify.reset)
      },
    },
  }
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: #fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-form-item.is-error .el-input__wrapper,
    .el-form-item.is-error .el-input__wrapper:focus {
      box-shadow: 0 0 0 0px;
    }

    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      // .el-input__wrapper {

      // }
      .el-input__wrapper,
      input {
        background: transparent;
        border: 0px;
        box-shadow: 0 0 0 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;
        width: 100%;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;
    // position: relative;

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .infohub {
      width: 100%;
      font-size: 12px;
      color: gray;
      text-align: center;
      bottom: 10px;
      position: fixed;

      .helpHub {
        display: flex;
        margin: auto;
        width: 240px;
        justify-content: space-around;
      }
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }
</style>
